var app = angular.module('conversionTool', []);

app.controller('operationMappingCtrl', [ '$scope', '$http', function($scope, $http) {

	$scope.operation = new Object();

	$scope.getOperation = function() {

		var id = $("#operationId").val();

		$http.post('/rest/project/getOperationById', id).success(function(data) {

			if (data != "" && data != undefined) {
				$scope.operation = data;

				if ($scope.operation.mapping == null || $scope.operation.mapping == undefined) {
					$scope.operation.mapping = new Object();
				}

			} else {
				$scope.operation.mapping = new Object();
			}

		}).error(function(data) {
			console.log(data);
		});

	}

	$scope.getOperation();

	$scope.getHeader = function() {

		var id = $("#operationId").val();

		$http.post('/rest/project/getHeaderByOperationById', id).success(function(data) {

			if (data != "" && data != undefined) {
				$scope.header = data;
			} else {
				$scope.msg = "header data is error";

			}

		}).error(function(data) {
			console.log(data);
		});

	}

	$scope.getHeader();

	$scope.getTreeData = function() {

		var id = $("#operationId").val();

		$http.post('/rest/project/XMLNode', id).success(function(data) {

			if (data != "" && data != undefined) {
				$scope.treeData = data;
				$scope.createTree();
			}

		}).error(function(data) {
			console.log(data);
		});

	}

	$scope.getTreeData();

	$scope.createTree = function() {
		$scope.$treeview = $("#tree");
		$scope.$treeview.jstree({
			'core' : {
				"check_callback" : true,
				"data" : $scope.treeData
			}
		}).on('loaded.jstree', function() {
			$scope.$treeview.jstree('open_all');
		}).on("select_node.jstree", function(e, data) {

			$("#nodeName").val(data.node.original.text);

			$("#nodePath").val(data.node.original.path);

			$("#nodeValue").val(data.node.original.value);

		});
	}

	$scope.addSetting = function() {
		
		
		
		$scope.operation.mapping[$("#nodePath").val()] = $("#nodeValue").val();

	}

	$scope.setHeader = function(item) {
		$("#nodeValue").val("header|" + item);
	}

	$scope.deleteNodeSetting = function(id) {
		delete $scope.operation.mapping[id];

	}

	$scope.save = function() {

		var operation = {
			"id" : $scope.operation.id,
			"mapping" : $scope.operation.mapping
		};
		$http.post('/rest/project/saveMapping', operation).success(function(data) {

			if (data == true) {

				$scope.msg = " save success!";
			} else {
				$scope.msg = "server saving error";

			}

		}).error(function(data) {
			console.log(data);
		});

	}

} ]);